package simulators;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.JButton;

import org.apache.log4j.Logger;

import config.ConfigData;

import drivers.TestDriver;

import types.TextMessage;
import javax.swing.JTextPane;

public class MessageSenderReceiverJFrame extends JFrame implements ActionListener
{
    private static final long serialVersionUID = 7037052265192839867L;
    private static final String SEND_MESSAGE = "SEND_MESSAGE";
    private static final String SHUT_DOWN_MESSAGE = "SHUT_DOWN_MESSAGE";
    private JPanel contentPane;
    private JTextField txtFromphonenumber;
    private JTextField txtMessageContents;
    private JButton btnSendMessage;
    private static Logger myLogger = Logger.getLogger(MessageSenderReceiverJFrame.class.getName());
    private JButton btnShutDown;
    private JTextPane txtpnHello;
    private Document doc;
    private Timer timer;

    /**
     * Create the frame.
     */
    public MessageSenderReceiverJFrame()
    {
    	setTitle("Text Message Generator");
	setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	setBounds(100, 100, 467, 375);
	contentPane = new JPanel();
	contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
	setContentPane(contentPane);
	GridBagLayout gbl_contentPane = new GridBagLayout();
	gbl_contentPane.columnWidths = new int[] {150, 150};
	gbl_contentPane.rowHeights = new int[] {15, 15, 0, 15, 15};
	gbl_contentPane.columnWeights = new double[]{1.0, 1.0};
	gbl_contentPane.rowWeights = new double[]{1.0, 1.0, 1.0, 1.0, 1.0};
	contentPane.setLayout(gbl_contentPane);
	
	JLabel lblFromPhoneNumber = new JLabel("From Phone Number:");
	GridBagConstraints gbc_lblFromPhoneNumber = new GridBagConstraints();
	gbc_lblFromPhoneNumber.anchor = GridBagConstraints.EAST;
	gbc_lblFromPhoneNumber.fill = GridBagConstraints.VERTICAL;
	gbc_lblFromPhoneNumber.insets = new Insets(0, 0, 5, 5);
	gbc_lblFromPhoneNumber.gridx = 0;
	gbc_lblFromPhoneNumber.gridy = 0;
	contentPane.add(lblFromPhoneNumber, gbc_lblFromPhoneNumber);
	
	txtFromphonenumber = new JTextField();
	GridBagConstraints gbc_txtFromphonenumber = new GridBagConstraints();
	gbc_txtFromphonenumber.insets = new Insets(0, 0, 5, 0);
	gbc_txtFromphonenumber.fill = GridBagConstraints.HORIZONTAL;
	gbc_txtFromphonenumber.gridx = 1;
	gbc_txtFromphonenumber.gridy = 0;
	contentPane.add(txtFromphonenumber, gbc_txtFromphonenumber);
	txtFromphonenumber.setColumns(10);
	
	JLabel lblMessageContents = new JLabel("Message Contents:");
	GridBagConstraints gbc_lblMessageContents = new GridBagConstraints();
	gbc_lblMessageContents.anchor = GridBagConstraints.EAST;
	gbc_lblMessageContents.insets = new Insets(0, 0, 5, 5);
	gbc_lblMessageContents.gridx = 0;
	gbc_lblMessageContents.gridy = 1;
	contentPane.add(lblMessageContents, gbc_lblMessageContents);
	
	txtMessageContents = new JTextField();
	GridBagConstraints gbc_txtMessageContents = new GridBagConstraints();
	gbc_txtMessageContents.insets = new Insets(0, 0, 5, 0);
	gbc_txtMessageContents.fill = GridBagConstraints.HORIZONTAL;
	gbc_txtMessageContents.gridx = 1;
	gbc_txtMessageContents.gridy = 1;
	contentPane.add(txtMessageContents, gbc_txtMessageContents);
	txtMessageContents.setColumns(10);
	
	btnSendMessage = new JButton("Send Message");
	GridBagConstraints gbc_btnSendMessage = new GridBagConstraints();
	gbc_btnSendMessage.insets = new Insets(0, 0, 5, 5);
	gbc_btnSendMessage.gridx = 0;
	gbc_btnSendMessage.gridy = 2;
	contentPane.add(btnSendMessage, gbc_btnSendMessage);
	btnSendMessage.setActionCommand(SEND_MESSAGE);
	btnSendMessage.addActionListener(this);
	
	btnShutDown = new JButton("Shut down");
	GridBagConstraints gbc_btnShutDown = new GridBagConstraints();
	gbc_btnShutDown.insets = new Insets(0, 0, 5, 0);
	gbc_btnShutDown.gridx = 1;
	gbc_btnShutDown.gridy = 2;
	contentPane.add(btnShutDown, gbc_btnShutDown);
	btnShutDown.setActionCommand(SHUT_DOWN_MESSAGE);
	
	txtpnHello = new JTextPane();
	txtpnHello.setText("Outgoing messages");
	txtpnHello.setBackground(Color.WHITE);
	GridBagConstraints gbc_txtpnHello = new GridBagConstraints();
	gbc_txtpnHello.gridheight = 2;
	gbc_txtpnHello.gridwidth = 2;
	gbc_txtpnHello.fill = GridBagConstraints.BOTH;
	gbc_txtpnHello.gridx = 0;
	gbc_txtpnHello.gridy = 3;
	contentPane.add(txtpnHello, gbc_txtpnHello);
	btnShutDown.addActionListener(this);
	doc = txtpnHello.getDocument();
	
	updateOutboxMessages();
	
    }

    public void actionPerformed(ActionEvent e)
    {
	// get command
	String cmd = e.getActionCommand();
	
	// compare to commands
	if(cmd.equals(SEND_MESSAGE))
	{
	    // Create text message from inputs
	    TextMessage tMessage = new TextMessage(txtFromphonenumber.getText(), txtMessageContents.getText());
	    
	    // Add to test inbox
	    MessageInbox.addMessage(tMessage);
	    
	    myLogger.info("Sent message: " + tMessage.toString());
	}
	else if(cmd.equals(SHUT_DOWN_MESSAGE))
	{ 
	    TestDriver.isAlive = false;
	    this.dispose();
	}	
    }
    
    public void updateOutboxMessages()
    {
	timer = new Timer("Outbox Sending");
	timer.scheduleAtFixedRate(new TimerTask()
	{
	    @Override
	    public void run()
	    {
		TextMessage tm = MessageOutbox.getMessage();
		
		while (null != tm)
		{
		    // Got message
		    myLogger.info("Found message in outbox: " + tm);
		    
		    // Do something with it
		    updateOutboxMessagesHelper(tm);
		    
		    // get another message
		    tm = MessageInbox.getMessage();
		}
	    }
	    
	}, 0, ConfigData.getMonitorRate());	
    }
    
    /**
     * Helper
     * 
     * @param tm
     */
    private void updateOutboxMessagesHelper(final TextMessage tm)
    {
	
	EventQueue.invokeLater(new Runnable()
	{
	    public void run()
	    {
		try
		{
		    String outputMsg = "\n[" + tm.getFromPhone() + "] - " + tm.getMessageContents();
		    //txtpnHello.setText(txtpnHello.getText() + "\n" + outputMsg);
		    doc.insertString(doc.getLength(), outputMsg, null);
		}
		catch (BadLocationException e)
		{
		    myLogger.error(
			    "Could not show outgoing TextMessage: " + tm, e);
		}
		
	//	validate();
	    }
	});
    }
}
